# Markdown批量自动添加前缀
import os
from datetime import datetime
file_path = 'D:\\devops\\devops\\docs'
today = datetime.strftime(datetime.now(), '%Y-%m-%d')


# 动态生成前缀
def set_prefix(title, date, cate):
    prefix = '''---
title: ''' + title + '''
date: ''' + date + '''
tags:
 - ''' + cate + '''
categories:
 - ''' + cate + '''
---
'''
    return prefix


# 开始批量添加前缀
def begin_add(rootdir,dir):
    list = os.listdir(rootdir)
    for i in range(len(list)):
        markdown = os.path.join(rootdir, list[i])
        addtxt=set_prefix(list[i], today,dir)
        if os.path.isfile(markdown):
            with open(markdown, 'r+',encoding='utf8') as f:
                content = f.read()
                f.seek(0, 0)
                f.write(addtxt + content)


if __name__ == '__main__':
    filelist = os.listdir(file_path)
    filelist.remove("img")
    all_path = []
    for dir in filelist:
        sec_path = file_path + os.sep + dir
        begin_add(sec_path,dir)


# 传入父路径，返回所有子路径
# def path_list(file_path):
#     filelist = os.listdir(file_path)
#     filelist.remove("img")
#     all_path = []
#     for dir in filelist:
#         sec_path = file_path + os.sep + dir
#         all_path.append(sec_path)
#         # print(sec_path + "-->" + str(os.listdir(sec_path)))
#     return all_path